package endpoint

import (
	"center/db"
	"common/pb"
	"common/uuid"
	"common/ws_contact"
	"context"
	"fmt"
	"go.uber.org/zap"
)

func (s *MetainfoServer) DeleteObjects(ctx context.Context, req *pb.ObjectDeleteRequest) (_ *pb.ObjectDeleteResponse, err error) {
	var streamId uuid.UUID
	defer func() {
		err = Error.Wrap(err)
		s.log.Info("DeleteObjects",
			zap.String("streamId", streamId.String()),
			zap.ByteString("bucket", req.Bucket), zap.ByteString("encryptedObjectKey", req.EncryptedObjectKey), zap.Error(err))
	}()
	apiKey, err := s.validateAuth(ctx, req.Header)
	if err != nil {
		return nil, err
	}

	//检查bucket是否存在
	bucket, err := s.db.GetBucketByName(ctx, string(req.Bucket), apiKey.Head())
	if err != nil {
		return nil, err
	}

	//todo node删除
	obj, err := s.db.GetObjectWithSegments(ctx, db.ObjectOne{BucketId: bucket.ID, EncryptObjectKey: req.EncryptedObjectKey})
	if err != nil {
		s.log.Error("get obj err", zap.Error(err))
		return nil, err
	}
	streamId = obj.StreamId

	for _, segment := range obj.Segments {
		for pieceIdx, nodeIdx := range segment.NodePieces {
			nodeId := s.db.NodeIdxToId(ctx, nodeIdx)
			pieceId := fmt.Sprintf("%x-%d-%d", string(obj.StreamId.Bytes()), segment.Position, pieceIdx)
			err = s.nodeClient.PieceDelete(nodeId, &ws_contact.PieceDeleteRequest{
				Key: pieceId,
			})
			if err != nil {
				s.log.Error("删除失败", zap.String("nodeId", nodeId.String()), zap.String("pieceId", pieceId), zap.Error(err))
			} else {
				s.log.Error("删除成功", zap.String("nodeId", nodeId.String()), zap.String("pieceId", pieceId))
			}
		}
	}
	err = s.db.DeleteObject(ctx, db.ObjectOne{BucketId: bucket.ID, EncryptObjectKey: req.EncryptedObjectKey})
	return &pb.ObjectDeleteResponse{Status: err == nil}, err
}
